# -*- coding: utf-8 -*-
import requests
import json

requests.packages.urllib3.disable_warnings()


def addtarget(domain):
    # 添加扫描目标,返回目标的target_id
    data = {"address": domain, "description": domain, "criticality": "10"}
    try:
        response = requests.post(wvsserver + "/api/v1/targets", data=json.dumps(data), headers=wvs_headers, verify=False)
        result = json.loads(response.content)
        return result['target_id']
    except Exception as e:
        print(e)
        return

def settarget(target_id):
    # 根据target_id对扫描目标进行爬虫和高级配置
    url = wvsserver + "api/v1/targets/" + target_id + "/configuration"
    data = {"limit_crawler_scope": False, "case_sensitive": "auto", "excluded_paths": "", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4298.0 Safari/537.36"}
    data2 = {"proxy": {"enabled": True, "protocol": "http", "address": "127.0.0.1", "port": 1111}}
    data3 = {"scan_speed": "moderate"}
    try:
        requests.patch(url, data=json.dumps(data), headers=wvs_headers, verify=False)  # 爬虫配置
        requests.patch(url, data=json.dumps(data2), headers=wvs_headers, verify=False)  # HTTP配置
        requests.patch(url, data=json.dumps(data3), headers=wvs_headers, verify=False)  # 扫描速度配置
    except Exception as e:
        print(e)
        return

def setscan(target_id):
    # 根据target_id开始扫描,返回扫描id
    data = {"target_id": target_id, "profile_id": "11111111-1111-1111-1111-111111111117",
            "schedule": {"disable": False, "start_date": None, "time_sensitive": False}}
    try:
        response = requests.post(wvsserver + "/api/v1/scans", data=json.dumps(data), headers=wvs_headers, verify=False)
        result = response.headers
        scan_id = result['Location'].split('/')[4]
        return scan_id
    except Exception as e:
        print(e)
        return

def scantask(domain):
    # 扫描每个域名
    target_id = addtarget(domain)
    settarget(target_id)
    setscan(target_id)


if __name__ == "__main__":
    wvsserver = "https://127.0.0.1:3443/"
    apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"  # 线上正式环境(8.134.8.171)
    wvs_headers = {"X-Auth": apikey, "content-type": "application/json"}
    # 读取域名数据
    with open('awvs.txt', 'r', encoding='utf-8') as f:
        login_data_list = f.read().splitlines()
    print(login_data_list)
    for domain in login_data_list:
        scantask(domain)
